// ConfigManager.h
#pragma once

#include <Arduino.h>
#include <EEPROM.h>
#include "HardwareConfig.h"

// WiFi配置结构
struct WiFiConfig
{
    char ssid[32];
    char password[64];
    bool isAP;          // true: AP模式, false: STA模式
    bool autoConnect;   // 启动时自动连接
    uint8_t maxRetries; // 最大重试次数

    WiFiConfig()
    {
        memset(ssid, 0, sizeof(ssid));
        memset(password, 0, sizeof(password));
        isAP = false;
        autoConnect = true;
        maxRetries = 5;
    }
};

// 蓝牙配置结构
struct BluetoothConfig
{
    char deviceName[32];
    bool bleEnabled;     // BLE使能
    bool classicEnabled; // 经典蓝牙使能
    bool discoverable;   // 可被发现
    uint32_t timeoutMs;  // 超时时间

    BluetoothConfig()
    {
        memset(deviceName, 0, sizeof(deviceName));
        bleEnabled = false;
        classicEnabled = false;
        discoverable = true;
        timeoutMs = 30000;
    }
};

// 网络配置结构
struct NetworkConfig
{
    char hostname[32];   // 设备主机名
    bool dhcpEnabled;    // DHCP使能
    uint8_t staticIP[4]; // 静态IP
    uint8_t gateway[4];  // 网关
    uint8_t subnet[4];   // 子网掩码
    uint8_t dns[4];      // DNS服务器

    NetworkConfig()
    {
        memset(hostname, 0, sizeof(hostname));
        dhcpEnabled = true;
        memset(staticIP, 0, sizeof(staticIP));
        memset(gateway, 0, sizeof(gateway));
        memset(subnet, 0, sizeof(subnet));
        memset(dns, 0, sizeof(dns));
    }
};

// 系统配置结构
struct SystemConfig
{
    uint32_t commandTimeout;    // 指令超时时间
    uint16_t bufferSize;        // 缓冲区大小
    bool autoSave;              // 自动保存配置
    uint8_t logLevel;           // 日志级别
    uint32_t heartbeatInterval; // 心跳间隔
    bool locked;                // 添加锁定状态
    char unlockPassword[32];    // 解锁密码

    SystemConfig()
    {
        commandTimeout = CMD_TIMEOUT_MS;
        bufferSize = CMD_BUFFER_SIZE;
        autoSave = true;
        logLevel = 1;
        heartbeatInterval = 60000;
        locked = true;                    // 默认锁定
        strcpy(unlockPassword, "123456"); // 默认密码
    }
};

// 完整的配置数据结构
struct ConfigData
{
    uint32_t magic;        // 魔数用于验证
    uint32_t version;      // 配置版本
    WiFiConfig wifi;       // WiFi配置
    BluetoothConfig bt;    // 蓝牙配置
    NetworkConfig network; // 网络配置
    SystemConfig system;   // 系统配置
    uint32_t crc;          // CRC校验
};

class ConfigManager
{
private:
    static const uint32_t CONFIG_MAGIC = 0x43504647;   // "CPFG"的十六进制
    static const uint32_t CONFIG_VERSION = 0x00010000; // 版本 1.0

    ConfigData config;
    bool configLoaded;

    uint32_t calculateCRC(const uint8_t *data, size_t length);
    void setDefaultConfig();
    bool validateConfig();

public:
    ConfigManager();
    ~ConfigManager();

    // 初始化配置系统
    bool begin();

    // 配置保存和加载
    bool save();
    bool load();
    bool resetToDefaults();

    // 配置验证
    bool isValid() const { return configLoaded; }
    bool hasWiFiConfig() const { return strlen(config.wifi.ssid) > 0; }
    bool hasBluetoothConfig() const { return strlen(config.bt.deviceName) > 0; }

    // WiFi配置访问
    WiFiConfig &getWiFiConfig() { return config.wifi; }
    const WiFiConfig &getWiFiConfig() const { return config.wifi; }
    void setWiFiConfig(const char *ssid, const char *password = nullptr,
                       bool isAP = false, bool autoConnect = true);
    void setWiFiAutoConnect(bool autoConnect) { config.wifi.autoConnect = autoConnect; }

    // 蓝牙配置访问
    BluetoothConfig &getBluetoothConfig() { return config.bt; }
    const BluetoothConfig &getBluetoothConfig() const { return config.bt; }
    void setBluetoothConfig(const char *deviceName, bool bleEnabled = true,
                            bool classicEnabled = false, bool discoverable = true);
    void setBluetoothMode(bool bleEnabled, bool classicEnabled);

    // 网络配置访问
    NetworkConfig &getNetworkConfig() { return config.network; }
    const NetworkConfig &getNetworkConfig() const { return config.network; }
    void setNetworkConfig(const char *hostname, bool dhcpEnabled = true);
    void setStaticIP(const uint8_t ip[4], const uint8_t gateway[4],
                     const uint8_t subnet[4], const uint8_t dns[4]);

    // 系统配置访问
    SystemConfig &getSystemConfig() { return config.system; }
    const SystemConfig &getSystemConfig() const { return config.system; }
    void setSystemConfig(uint32_t commandTimeout = CMD_TIMEOUT_MS,
                         uint16_t bufferSize = CMD_BUFFER_SIZE,
                         bool autoSave = true, uint8_t logLevel = 1);

    // 工具方法
    void printConfig(); // 调试用：打印当前配置
    uint32_t getConfigSize() const { return sizeof(ConfigData); }
    uint32_t getConfigVersion() const { return config.version; }

    // 配置变更回调（可选实现）
    typedef void (*ConfigChangeCallback)(const char *section, void *userData);
    void setConfigChangeCallback(ConfigChangeCallback callback, void *userData = nullptr);

    void setLocked(bool locked)
    {
        config.system.locked = locked;
        notifyConfigChange("system");
    }

    void setUnlockPassword(const char *password)
    {
        strncpy(config.system.unlockPassword, password, sizeof(config.system.unlockPassword) - 1);
        config.system.unlockPassword[sizeof(config.system.unlockPassword) - 1] = '\0';
        notifyConfigChange("system");
    }

private:
    ConfigChangeCallback configCallback;
    void *callbackUserData;
    void notifyConfigChange(const char *section);
};